package com.example.hrsystem.ui.approval.business;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;

import com.example.hrsystem.R;
import com.example.hrsystem.workflow.ApprovalViewModel;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class BusinessTravelRequestFormActivity extends AppCompatActivity {
    private ApprovalViewModel mViewModel;
    private Spinner mTravelTypeSpinner;
    private TextView mStartDateTextView, mEndDateTextView;
    private EditText mDestinationEditText, mPurposeEditText, mBudgetEditText;
    private Button mSubmitButton;
    private Calendar mStartCalendar, mEndCalendar;
    private SimpleDateFormat mDateFormat;
    private View mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_business_travel_request_form);

        setupToolbar();
        initViews();
        setupViewModel();
        setupDatePickers();
        setupSpinner();
        setupSubmitButton();
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(R.string.new_business_travel_request);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    private void initViews() {
        mTravelTypeSpinner = findViewById(R.id.travel_type_spinner);
        mStartDateTextView = findViewById(R.id.start_date_text_view);
        mEndDateTextView = findViewById(R.id.end_date_text_view);
        mDestinationEditText = findViewById(R.id.destination_edit_text);
        mPurposeEditText = findViewById(R.id.purpose_edit_text);
        mBudgetEditText = findViewById(R.id.budget_edit_text);
        mSubmitButton = findViewById(R.id.submit_button);
        mProgressBar = findViewById(R.id.progress_bar);

        mStartCalendar = Calendar.getInstance();
        mEndCalendar = Calendar.getInstance();
        mEndCalendar.add(Calendar.DAY_OF_MONTH, 1); // 默认结束日期为明天
        mDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

        mStartDateTextView.setText(mDateFormat.format(mStartCalendar.getTime()));
        mEndDateTextView.setText(mDateFormat.format(mEndCalendar.getTime()));
    }

    private void setupViewModel() {
        mViewModel = new ViewModelProvider(this).get(ApprovalViewModel.class);
        mViewModel.getIsLoading().observe(this, isLoading -> {
            mProgressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
            mSubmitButton.setEnabled(!isLoading);
        });

        // 暂时注释掉，因为getRequestResult方法不存在
        /*mViewModel.getRequestResult().observe(this, result -> {
            if (result != null && result.isSuccess()) {
                Toast.makeText(this, R.string.request_submitted_successfully, Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                finish();
            } else {
                String errorMessage = result != null ? result.getErrorMessage() : getString(R.string.failed_to_submit_request);
                Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });*/
    }

    private void setupDatePickers() {
        mStartDateTextView.setOnClickListener(v -> {
            new DatePickerDialog(BusinessTravelRequestFormActivity.this,
                    (view, year, month, dayOfMonth) -> {
                        mStartCalendar.set(year, month, dayOfMonth);
                        mStartDateTextView.setText(mDateFormat.format(mStartCalendar.getTime()));
                    },
                    mStartCalendar.get(Calendar.YEAR),
                    mStartCalendar.get(Calendar.MONTH),
                    mStartCalendar.get(Calendar.DAY_OF_MONTH)).show();
        });

        mEndDateTextView.setOnClickListener(v -> {
            new DatePickerDialog(BusinessTravelRequestFormActivity.this,
                    (view, year, month, dayOfMonth) -> {
                        Calendar selectedDate = Calendar.getInstance();
                        selectedDate.set(year, month, dayOfMonth);

                        if (selectedDate.before(mStartCalendar)) {
                            Toast.makeText(BusinessTravelRequestFormActivity.this,
                                    R.string.end_date_must_be_after_start_date, Toast.LENGTH_SHORT).show();
                            return;
                        }

                        mEndCalendar = selectedDate;
                        mEndDateTextView.setText(mDateFormat.format(mEndCalendar.getTime()));
                    },
                    mEndCalendar.get(Calendar.YEAR),
                    mEndCalendar.get(Calendar.MONTH),
                    mEndCalendar.get(Calendar.DAY_OF_MONTH)).show();
        });
    }

    private void setupSpinner() {
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.travel_type_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mTravelTypeSpinner.setAdapter(adapter);
    }

    private void setupSubmitButton() {
        mSubmitButton.setOnClickListener(v -> {
            if (validateForm()) {
                submitRequest();
            }
        });
    }

    private boolean validateForm() {
        if (TextUtils.isEmpty(mDestinationEditText.getText().toString().trim())) {
            mDestinationEditText.setError(getString(R.string.please_enter_destination));
            return false;
        }

        if (TextUtils.isEmpty(mPurposeEditText.getText().toString().trim())) {
            mPurposeEditText.setError(getString(R.string.please_enter_purpose));
            return false;
        }

        if (TextUtils.isEmpty(mBudgetEditText.getText().toString().trim())) {
            mBudgetEditText.setError(getString(R.string.please_enter_budget));
            return false;
        }

        return true;
    }

    private void submitRequest() {
        String travelType = mTravelTypeSpinner.getSelectedItem().toString();
        String startDate = mStartDateTextView.getText().toString();
        String endDate = mEndDateTextView.getText().toString();
        String destination = mDestinationEditText.getText().toString().trim();
        String purpose = mPurposeEditText.getText().toString().trim();
        double budget = Double.parseDouble(mBudgetEditText.getText().toString().trim());

        // 计算出差天数
        long diff = mEndCalendar.getTimeInMillis() - mStartCalendar.getTimeInMillis();
        int days = (int) (diff / (1000 * 60 * 60 * 24)) + 1; // +1 包含开始日期

        // 提交请求到ViewModel
        // 暂时注释掉，因为submitBusinessTravelRequest方法不存在
        /*mViewModel.submitBusinessTravelRequest(travelType, startDate, endDate, days, destination, purpose, budget);*/
        // 显示临时成功消息
        Toast.makeText(this, "出差申请已提交", Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}